package com.idbk.chargestation.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.android.volley.toolbox.StringRequest;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.user.ActivityLogin;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.view.EToolbar2;

/**
 * activity的轻封装，处理公共的一些逻辑
 * @author lupc, zhx
 *
 */
public class BaseActivity extends AppCompatActivity {

	protected StringRequest mMainRequest;
	protected ProgressDialog mMainProgressDialog;
	private String mToolbarTitle;
	protected EToolbar2 mToolbar2;

	protected void setupToolBar2() {
		mToolbar2 = (EToolbar2) findViewById(R.id.tj_toolbar2);
		mToolbar2.setTitle(getToolBarTitle());
		mToolbar2.getBackView().setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});	
	}	

	protected void setToolbar2Title(String title){
		mToolbarTitle = title;
		mToolbar2.setTitle(title);
	}

	protected String getToolBarTitle(){
		if(mToolbarTitle == null){
			return getTitle().toString();
		} else {
			return mToolbarTitle;
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void cancelCurrentRequest(){
		if(mMainRequest != null){
			mMainRequest.cancel();
		}
	}
	
	/**
	 * 显示等待框
	 * @param canCancel 取消的时候 是否取消请求
	 * @param finish 取消的时候 是否关闭当前activity
	 * @param msg 显示的内容
	 */
	protected void showMyProgressDialog(final boolean canCancel, final boolean finish, String msg){
		mMainProgressDialog = ProgressDialog.show(this, null, msg, true, true,
				new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				if(canCancel){
					cancelCurrentRequest();	
				}
				if(finish){
					finish();
				}
			}
		});
		mMainProgressDialog.setCanceledOnTouchOutside(false);
	}
	
	protected void dismissMyProgressDialog(){
		if(mMainProgressDialog != null){
			mMainProgressDialog.dismiss();
		}
	}

	public static void showResult(final Context context,String msg,final boolean finish){
		new AlertDialog.Builder(context)
		.setMessage(msg)
		.setCancelable(false)
		.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(finish && context instanceof Activity){
					((Activity)context).finish();
				}
			}
		})
		.create()
		.show();
	}
	
	/**
	 * 通用结果处理，主要处理登录状态
	 * @param context context
	 * @param result 网络返回的结果
	 * @return 是否返回需要解析的数据
	 */
	public static boolean handleResponseStatus(final Context context,JsonBase result){
		if(result == null){
			Toast.makeText(
					context,
					R.string.common_tip_rusultzero, 
					Toast.LENGTH_SHORT)
					.show();
			return false;
		}
		if(result.status == GlobalResult.OK.getStatus()) {
			return true;
		} else if(result.status == GlobalResult.TOKEN_INVALID.getStatus()
				|| result.status == GlobalResult.TOKEN_REQUIRED.getStatus()) {	
			AppContext.getInstance().clearLoginState();//清除登录状态
			new AlertDialog.Builder(context)
			.setTitle(R.string.common_dialog_tip)
			.setMessage("登录超时，请重新登录！")
			.setCancelable(false)
			.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(context, ActivityLogin.class);
					context.startActivity(intent);
				}
			})
			.create()
			.show();	
			return false;
		} else {
			Toast.makeText(
					context, 
					result.message, 
					Toast.LENGTH_SHORT)
					.show();
			return false;
		}
	}

	/**
	 * 通用的结果处理，主要处理登录状态
	 * @param activity activity
	 * @param result 返回的结果
	 * @return 是否返回需要解析的数据
	 */
	public static boolean handleResponseStatus(final Activity activity,JsonBase result){
		if(result == null){
			Toast.makeText(
					activity,
					R.string.common_tip_rusultzero, 
					Toast.LENGTH_SHORT)
					.show();
			return false;
		}
		if(result.status == GlobalResult.OK.getStatus()) {
			return true;
			
		} else if(result.status == GlobalResult.TOKEN_INVALID.getStatus()
				|| result.status == GlobalResult.TOKEN_REQUIRED.getStatus()) {	
			jumpToLogin(activity, true);
			return false;
			
		} else {
			Toast.makeText(
					activity, 
					result.message, 
					Toast.LENGTH_SHORT)
					.show();
			return false;
		}
	}
	
	/**
	 * 清除登陆状态，跳转到登陆界面
	 * @param activity 当前activity
	 * @param isFinish 是否结束传入的activity
	 */
	public static void jumpToLogin(final Activity activity, final boolean isFinish) {
		AppContext.getInstance().clearLoginState();//清除登录状态
		new AlertDialog.Builder(activity)
		.setTitle(R.string.common_dialog_tip)
		.setMessage("登录超时，请重新登录！")
		.setCancelable(false)
		.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {				
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (isFinish) {
					activity.finish();
				}
				Intent intent = new Intent(activity, ActivityLogin.class);
				activity.startActivity(intent);
			}
		})
		.create()
		.show();	
	}
	
	protected boolean handleResponseStatus(JsonBase result) {
		return handleResponseStatus(this,result);
	}

	/**
	 * 检查是否已经登录
	 * @param jumpLoginActivity 如果没有登录，是否跳转到登录界面
	 * @return 是否已跳转到登陆界面
	 */
	public final boolean checkLogin(boolean jumpLoginActivity){
		AppContext ac = AppContext.getInstance();
		if(ac == null || !ac.isLogin()){
			if(jumpLoginActivity){
				Intent intent = new Intent(this, ActivityLogin.class);
				startActivity(intent);
			}
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 隐藏输入键盘
	 */
	protected void hideKeyboard() {
		View view = getCurrentFocus();
		if (view != null) {
			((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
			hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
	
	/**
	 * 判断字符是否包含表情
	 * @param source 字符串
	 * @return 是否包含表情
	 */
	protected boolean containsEmoji(String source){
		int len = source.length(); 
		for (int i = 0; i < len; i++) { 
			char codePoint = source.charAt(i); 
			if (!isEmojiCharacter(codePoint)) { 
				//如果不能匹配,则该字符是Emoji表情 
				return true; 
			}
		}
		return false;
	}
	
	/** * 判断是否是Emoji *
	 *  @param codePoint 比较的单个字符 * 
	 *  @return 是否包含表情
	 *  */ 
	private static boolean isEmojiCharacter(char codePoint) { 
		return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) 
				|| (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) 
				|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD));
//				|| ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)
	}

	/**
	 * 显示提示信息
	 * @since 2.5.0
	 */
	protected void showMissingPermissionDialog() {
		showMissingPermissionDialog(this);
	}
	
	public static void showMissingPermissionDialog(final Activity activity){
		new AlertDialog.Builder(activity)
		.setTitle("提示")
		.setMessage("当前应用缺少必要权限。\n\n请点击\"设置\"-\"权限\"-打开所需权限。")
		.setNegativeButton(R.string.common_cancel,null)
		.setPositiveButton("设置",
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				startAppSettings(activity);
			}
		})
		.setCancelable(false)
		.create()
		.show();
	}

	/**
	 *  启动应用的设置
	 * @since 2.5.0
	 */
	private static void startAppSettings(Activity activity) {
		Intent intent = new Intent(
				Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		intent.setData(Uri.parse("package:" + activity.getPackageName()));
		activity.startActivity(intent);
	}

}
